import cgi
import urllib
import random
import string

import gdata.blogger.client
import gdata.client
import gdata.sample_util
import gdata.data
import atom.data
import gdata.alt.appengine
import gdata.service
import gdata.auth

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

from appengine_utilities.sessions import Session

class MainPage(webapp.RequestHandler):
	def get(self):
		self.session = Session()
	
		waveid = self.request.get('waveid')
		token = self.request.get('token')

		blogid = self.request.get('blogid')
		
		if blogid and waveid:
			#Check session token
			session_token=self.session['session_token']
			if not session_token:
				self.response.out.write("Session token missing.")
				return None
			else:
				#Create Google Data client
				blogger_service = gdata.service.GDataService()
				gdata.alt.appengine.run_on_appengine(blogger_service) #indicates that the apps works on appengine
				blogger_service.current_token = session_token
				
				#Publish new draft post with Embeded Wave
				if self.CreateDraftPost(blogger_service, blogid, waveid):
					self.response.out.write('A new draft post is added to your blog.')
				else:
					self.response.out.write('Something went wrong.')
				return None

		if not waveid or not token:
			self.response.out.write("Invalid request")
			return None
		
		else:
			#Create Google Data client
			blogger_service = gdata.service.GDataService()
			gdata.alt.appengine.run_on_appengine(blogger_service) #indicates that the apps works on appengine
		
			#Find token in URL and update to session token
			auth_token = gdata.auth.extract_auth_sub_token_from_url(self.request.uri)
			session_token = blogger_service.upgrade_to_session_token(auth_token)
			blogger_service.current_token = session_token
			
			#Remember the session token for second request
			self.session['session_token']=session_token
			
			self.PrintInfo(waveid, token)
			self.PrintBlogLinks(blogger_service, session_token, waveid)
		
		
	def PrintInfo(self, waveid, token):
		#Print the informations on the main website
		self.response.out.write('This is a very trivial Wave robot that helps to publish your waves directly on your Blogger blog.<br/>')
		self.response.out.write('Your waveid: ')
		self.response.out.write(waveid.replace(" ","+"))
		self.response.out.write('<br />')
		self.response.out.write(waveid)
		#self.response.out.write('token: ')
		#self.response.out.write(token)
		self.response.out.write('<br />')
		
	def PrintBlogLinks(self, blogger_service, session_token, waveid):
		#Get current users blogs
		feed_url = 'http://www.blogger.com/feeds/default/blogs'
		response = blogger_service.Get(feed_url)
		self.response.out.write('Choose the blog to publish on:<br/>')
		self.response.out.write('<ul>')
		for entry in response.entry:
			#get blog id - needed for publishing
			id = entry.id.text
			parts = id.split('-')
			blog_id = parts[2]
			#create link with blogid and waveid in GET
			url=urllib.urlencode({'blogid': blog_id, 'waveid':waveid})
			self.response.out.write("<li><a href='?%s'>%s</a></li>" % (url,entry.title.text))
		self.response.out.write('</ul>')
	
	def CreateDraftPost(self, blogger_service, blogid, waveid):
		#blog_id = '126560556880687203'
		title = 'Wave blogging'
		
		#Create random div id
		divid = ''.join([random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890') for i in range(21)])
		
		#Fix missing + in waveid after get
		waveid = waveid.replace(" ","+")
		
		content = '<script>showWave(\'%s\',\'%s\');</script>' % (divid,waveid)
		entry = gdata.GDataEntry()
		entry.title = atom.Title('xhtml', title)
		entry.content = atom.Content(content_type='html', text=content)
		
		control = atom.Control()
		control.draft = atom.Draft(text='yes')
		entry.control = control
		
		url = 'http://www.blogger.com/feeds/'+blogid+'/posts/default'
		return blogger_service.Post(entry, url)
		



application = webapp.WSGIApplication([('/', MainPage)], debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()